package NewChatRoom;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class ChatThreadManager {
    static ResultToServer rs = new ResultToServer();
    private static UserInfo sys = new UserInfo("系统","admin");
    private static List<serverHandlerThread> serverThreadList = new ArrayList<>();
    //单例
    private ChatThreadManager(){
    }
    public static List<serverHandlerThread> getAllServThread(){
        return serverThreadList;
    }

    public static void addClient(serverHandlerThread ctThread){
        //通知一下大家，有人上线
        serverThreadList.add(ctThread);
        castMsg(ctThread.getOwnUser(),"我上线了！(目前人数:"+serverThreadList.size()+")");
        //更新一下GUI
        SwingUtilities.updateComponentTreeUI(ServerGUI.table_online);
    }
    public static void sendMsgToOne(int index,String msg){
        //给队列中某位发送消息
        serverThreadList.get(index).sendMsgToClient(msg);
    }
    public static UserInfo getUserInfo(int index){
        return serverThreadList.get(index).getOwnUser();
    }

    public static void removeClient(int index){
        sendMsgToOne(index,"您已经被踢出群聊");
        serverHandlerThread sht = serverThreadList.remove(index);
        sht.closeMe();
        castMsg(sys,"踢出了用户"+sht.getOwnUser().getName());
    }
    public static void ClientExit(UserInfo userInfo){
        serverHandlerThread sht;
        for(int i = 0;i<serverThreadList.size();i++){
            sht = serverThreadList.get(i);
            if(sht.getOwnUser().getName().equals(userInfo.getName())){
                serverThreadList.remove(i);
                sht.closeMe();
                castMsg(userInfo,"我下线了");
            }
        }
    }
    //关闭服务器时调用
    public static void removeAllClient(){
        if(serverThreadList.isEmpty())
            return;
        int size = serverThreadList.size();
        for(int i = 0;i<size;i++){
            serverHandlerThread sht = serverThreadList.remove(0);
            sht.sendMsgToClient("系统消息：本服务器即将关闭");
            sht.closeMe();
            rs.print("关闭Handler"+sht.getOwnUser().getName()+"\n");
            sht = null;
        }
        rs.print("客户端删除完毕\n");
    }
    //广播信息
    public static void castMsg(UserInfo sender,String msg){
        msg = sender.getName() + "说："+msg;
        for(int i = 0;i<serverThreadList.size();i++){
            serverHandlerThread sht = serverThreadList.get(i);
            sht.sendMsgToClient(msg);
        }
    }
    public static void castMsg(String msg){
        msg = sys.getName() + "说："+msg;
        rs.print(msg+"\n");
        for(int i = 0;i<serverThreadList.size();i++){
            serverHandlerThread sht = serverThreadList.get(i);
            sht.sendMsgToClient(msg);
        }
    }
}
